package com.wchat.interceptor;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.wchat.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 请求拦截器，统一鉴权
 * @author : willian fu
 * @date : 2021/5/31
 */
@Configuration
public class PermInterceptor implements HandlerInterceptor, WebMvcConfigurer {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tk = request.getHeader("token");
        if (DigestUtil.md5Hex16("wchat@2021..").equals(tk) || ObjectUtil.isNotNull(jwtUtil.jwtGetUser())){
            return true;
        }
        response.setCharacterEncoding("utf-8");
        response.sendError(HttpStatus.UNAUTHORIZED.value(), "抱歉，您无权访问本接口 😥");
        return false;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //过滤请求
        registry.addInterceptor(this)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/static/**",
                        "/**.css",
                        "/**.js",
                        "/**.html",
                        "/error**",
                        "/user/login**",
                        "/user/register**",
                        "/media/upload/avatar**",
                        "/media/get/avatar**"
                );
    }
}
